package com.atguigu.juc.day03.scene;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class Demo02CyclingBarrier {

    public static List<List<String>> metricList;

    static {
        metricList = new ArrayList<>();
        metricList.add(Arrays.asList("normal", "special", "end"));
        metricList.add(Arrays.asList("normal", "normal", "special", "end"));
        metricList.add(Arrays.asList("normal", "normal", "normal", "special", "end"));
        metricList.add(Arrays.asList("normal", "normal", "normal", "normal", "special", "end"));
        metricList.add(Arrays.asList("normal", "normal", "normal", "normal", "normal", "special", "end"));
        metricList.add(Arrays.asList("normal", "normal", "normal", "normal", "normal", "normal", "normal", "special", "end"));
    }

    public static void main(String[] args) {

        CyclicBarrier cyclicBarrier = new CyclicBarrier(metricList.size());

        for (int i = 0; i < metricList.size(); i++) {
            int index = i;
            new Thread(()->{

                List<String> dataList = metricList.get(index);

                for (int j = 0; j < dataList.size(); j++) {
                    String data = dataList.get(j);
                    System.out.println("data = " + data + " " + Thread.currentThread().getName());

                    if ("special".equals(data)) {
                        try {
                            // 每一个线程达到指定位置时就抑制后续操作，等所有线程都到这里再一起去执行后续操作
                            cyclicBarrier.await();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        } catch (BrokenBarrierException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }

            }, "thread-" + i).start();
        }

    }

}
